MVC三層架構

MVC三層架構

public interface StudentDao {  
  
    Student getById(Integer studentId);  
  
    List<Student> getAll();  
  
    String deleteById(Integer studentId);  
  
    String add(Student student);  
  
    String addBatch(List<Student> studentList);  

@Component  //使用component註解使其成為bean
public class StudentDaoImpl implements StudentDao {  
  
    @Autowired  
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;  
  
    @Override  
    public Student getById(Integer studentId) {  
        String sql = "SELECT id, name FROM student WHERE id= :studentId";  
        Map<String, Object> map = new HashMap<>();  
        map.put("studentId", studentId);  
        List<Student> students = namedParameterJdbcTemplate.query(sql, map,new StudentRowMapper());  
        return students.isEmpty() ? null : students.get(0);  
    }
    //...以下各種實作
public interface StudentService {  
  
    Student getById(Integer studentId);  
  
    List<Student> getAll();  
  
    String deleteById(Integer studentId);  
  
    String add(Student student);  
  
    String addBatch(List<Student> studentList);  
}//基本上與dao一樣
@Component  
public class StudentServiceImpl implements StudentService{  
  
    @Autowired  //使用autowired使用dao的bean
    private StudentDao studentDao;  
    @Override  
    public Student getById(Integer studentId) {  
        return studentDao.getById(studentId);  
    }  
    @Override  
    public List<Student> getAll() {  
        return studentDao.getAll();  
    }
    //......
@RestController  
public class StudentController {  
    @Autowired  
    //同樣使用autowired使用bean
    private StudentService studentService;  
  
    @PostMapping("/students")  
    public String insert(@RequestBody Student student) {  
        return studentService.add(student);  
    }  
    @PostMapping("/students/batch")  
    public String insertBatch(@RequestBody List<Student> studentList) {  
        return studentService.addBatch(studentList);  
    }
    //......